<template>
  <div>
    <div>{{ user.name }}的{{ cart.name }} </div>
  </div>
  <table>
    <thead>
      <tr>
        <th width="200px">书名</th>
        <th width="200px">价格</th>
        <th width="200px">数量</th>   
        <th width="200px">操作</th>             
      </tr>      
    </thead>
    <tbody>
      <tr v-for="book of cart.books" :key="book.name">        
        <td>{{ book.name }}</td>
        <td>{{ book.price }}</td>
        <td>{{ book.count }}</td>
        <td>
          <button @click="add(book)">+</button>
          <button @click="minus(book)">-</button>
        </td>
      </tr>      
    </tbody>
  </table>
  <div>
    <button @click="batchAdd">全部加到10本</button>
    <button @click="batchAddMicroService">微服务加到10本</button>

    <button @click="cart.changeDiscountRate()">随机折扣</button>
    <p>折扣率：{{ cart.discountRate }}</p>
    <p>折后价格：{{ cart.price*cart.discountRate }}</p>
    <p>总价：{{ cart.price }}</p>

    <button @click="reset()">重置</button>
  </div>

 
  
</template>

<script setup lang="ts">
 import { onMounted, computed,onUnmounted } from 'vue'
import useAppStore from './store/index'
import { storeToRefs } from 'pinia'
import type { BookItem } from "./store/cart";

const store = useAppStore()

console.log(store)

// ⚠️⚠️ 返回的是一个 reactive 对象，不能直接解构哦，使用 pinia 提供的 storeToRefs API
const { user, cart, } = storeToRefs(useAppStore())


console.log('user',user)
console.log('cart',cart)

onUnmounted(() => {
  console.log('组件销毁')
  //  unsubscribe()
})

// const price = computed(() => {
//   let total = 0;
//   for (const book of books.value) {
//     total += book.price * book.count;
//   }
//   return total;
// });

const reset = () => {
  // 通过 $reset 方法重置 store
  // store.$reset();
  store.cart.$reset();
};

const add = (book: BookItem) => {
  
  book.count++;
};

const minus = (book: BookItem) => {
  if(book.count==0) return;
  book.count--;
};

const batchAdd = () => {
  // 通过 $patch 方法修改 store 多个字段
  store.$patch({
    cart: {
      name: '新购物车',
      books: [
        {
          name: "ES6",
          price: 50,
          count: 10,
        },
        {
          name: "微服务架构设计模式",
          price: 139,
          count: 10,
        },
        {
          name: "数据密集型应用系统设计",
          price: 128,
          count: 10,
        },
      ],
    }
  });
};
const batchAddMicroService = () => {
  store.$patch((state) => {
    state.cart.books[1].count = 10;
  });
}

// 用于监听 state 及其 mutation 动作
store.$subscribe((mutation, state) => {
  console.log(mutation);
  console.log(state);
});

 



const unsubscribe = store.$onAction(
 ({
    name,
    store,
    args,
    after,
    onError,
  }) => {
    const startTime = Date.now()
    console.log(`Start "${name}" with params [${args.join(', ')}].`)

    after((result) => {
      // resolve
      console.log(
        `Finished "${name}" after ${
          Date.now() - startTime
        }ms.\nResult: ${result}.`
      )
    })

    onError((error) => {
      // action  reject 时触发
      console.warn(
        `Failed "${name}" after ${Date.now() - startTime}ms.\nError: ${error}.`
      )
    })
 }, true
)
</script>




<style scoped>
.logo {
  height: 6em;
  padding: 1.5em;
  will-change: filter;
  transition: filter 300ms;
}
.logo:hover {
  filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.vue:hover {
  filter: drop-shadow(0 0 2em #42b883aa);
}
</style>
